const RIPPLE_DROP_INTERVAL = 4000;
let autoDropInterval = null;
let rippleEffectActive = false;

function initRipplesEffect() {
    if (rippleEffectActive) return;

    const $rippleContainer = $('#ripple-container');
    if (!$rippleContainer.length) return;

    try {
        const bgImg = document.body.style.backgroundImage;
        if (!bgImg || bgImg === 'none') {
            setTimeout(initRipplesEffect, 100);
            return;
        }

        $rippleContainer.css({
            'background-image': bgImg,
            'background-size': 'cover',
            'background-position': 'center'
        });

        if ($rippleContainer.data('ripples')) {
            $rippleContainer.ripples('destroy');
        }

        $rippleContainer.ripples({
            resolution: 200,
            dropRadius: 30,
            perturbance: 0.005,
            interactive: true
        });

        rippleEffectActive = true;

        clearInterval(autoDropInterval);
        autoDropInterval = setInterval(() => {
            if (!rippleEffectActive || document.visibilityState === 'hidden') return;

            const $el = $rippleContainer;
            const x = Math.random() * $el.outerWidth();
            const y = Math.random() * $el.outerHeight();
            $el.ripples('drop', x, y, 20, 0.15);
        }, RIPPLE_DROP_INTERVAL);

    } catch (e) {
        console.error('波纹效果初始化失败:', e);
        rippleEffectActive = false;
    }
}

function destroyRipplesEffect() {
    rippleEffectActive = false;
    clearInterval(autoDropInterval);
    autoDropInterval = null;

    const $rippleContainer = $('#ripple-container');
    if ($rippleContainer.data('ripples')) {
        $rippleContainer.ripples('destroy');
    }
}

document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
        destroyRipplesEffect();
    } else {
        initRipplesEffect();
    }
});

function handleResize() {
    if (rippleEffectActive) {
        destroyRipplesEffect();
        initRipplesEffect();
    }
}

$(document).ready(() => {
    setTimeout(() => {
        if (document.body.style.backgroundImage &&
            document.body.style.backgroundImage !== 'none') {
            initRipplesEffect();
        }
    }, 500);
});

window.addEventListener('resize', () => {
    clearTimeout(handleResize.timeout);
    handleResize.timeout = setTimeout(handleResize, 250);
});